package com.example.mypetstoreback.controller;

import cn.hutool.core.io.FileUtil;
import com.example.mypetstoreback.common.CommonResponse;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.ssl.SslProperties;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.transform.Result;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    private static final String ROOT_PATH = System.getProperty("user.dir") + File.separator+"files";

    @PostMapping("/upload")
    public CommonResponse<String> upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename(); //获得文件初始名称
        String mainName = FileUtil.mainName(originalFilename);
        String extName = FileUtil.extName("文件的后缀");

        //判断文件目录是否存在，若无则创建
        if (!FileUtil.exist(ROOT_PATH)){
            FileUtil.mkdir(ROOT_PATH);
        }

        if (FileUtil.exist(ROOT_PATH +File.separator+ originalFilename)){ //如果上传的文件存在 ->重命名文件名称
            originalFilename =System.currentTimeMillis() +mainName+"."+extName;
        }
        File saveFile = new File(ROOT_PATH+File.separator+originalFilename) ;
        file.transferTo(saveFile);//存储文件到本地磁盘
        String url = "http://localhost:8081/file/download/"+originalFilename;
        return CommonResponse.createForSuccess(url);//返回文件的链接，这个链接是文件的下载地址（后台提供
    }
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        String filePath = ROOT_PATH + File.separator +fileName;
        if (!FileUtil.exist(filePath)){
            return;
        }
        byte[] bytes= FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);  //文件字节流数组
        outputStream.flush();
        outputStream.close();
    }
}
